package org.tio.sitexxx.web.server.controller.base;

import java.awt.image.BufferedImage;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.tio.core.Tio;
import org.tio.http.common.HttpConfig;
import org.tio.http.common.HttpRequest;
import org.tio.http.common.UploadFile;
import org.tio.http.common.session.HttpSession;
import org.tio.http.server.annotation.RequestPath;
import org.tio.sitexxx.service.model.main.Img;
import org.tio.sitexxx.service.model.main.User;
import org.tio.sitexxx.service.service.ImgService;
import org.tio.sitexxx.service.service.base.UserRoleService;
import org.tio.sitexxx.service.service.base.UserService;
import org.tio.sitexxx.service.service.conf.ConfService;
import org.tio.sitexxx.service.vo.AppCode;
import org.tio.sitexxx.service.vo.Const;
import org.tio.sitexxx.service.vo.SessionExt;
import org.tio.sitexxx.service.vo.SessionKey;
import org.tio.sitexxx.service.vo.SimpleUser;
import org.tio.sitexxx.web.server.utils.ImgUtils;
import org.tio.sitexxx.web.server.utils.UploadUtils;
import org.tio.sitexxx.web.server.utils.WebUtils;
import org.tio.utils.resp.Resp;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ImageUtil;

/**
 * @author tanyaowu
 * 2016年6月29日 下午7:53:59
 */
@RequestPath(value = "/user")
public class UserController {
	private static Logger log = LoggerFactory.getLogger(UserController.class);

	private UserService userService = UserService.ME;

	/**
	 * @param args
	 * @author tanyaowu
	 */
	public static void main(String[] args) {
	}

	/**
	 *
	 * @author tanyaowu
	 */
	public UserController() {
	}

	/**
	 * 获取当前用户
	 * @param request
	 * @return
	 * @throws Exception
	 * @author tanyaowu
	 */
	@RequestPath(value = "/curr")
	public Resp curr(HttpRequest request) throws Exception {
		User user = WebUtils.currUser(request);
		if (user != null) {
			Resp resp = Resp.ok(user);
			//			HttpResponse ret = Resps.json(request, resp);
			return resp;
		} else {

			Resp resp = Resp.fail();
			//				HttpResponse ret = Resps.json(request, resp);
			return resp;
		}
	}

	/**
	 * 根据token，获取用户ID（此处的token其实就是sessionId）
	 * @param request
	 * @param httpConfig
	 * @param token
	 * @return
	 * @throws Exception
	 * @author: tanyaowu
	 */
	@RequestPath(value = "/byToken")
	public Resp byToken(HttpRequest request, HttpConfig httpConfig, String token) throws Exception {

		String sessionId = token;
		HttpSession httpSession = httpConfig.getHttpSession(sessionId);

		if (httpSession != null) {
			SessionExt sessionExt = httpSession.getAttribute(SessionKey.SESSION_EXT, SessionExt.class);
			Integer userid = sessionExt.getUid();

			if (userid != null) {
				Resp resp = Resp.ok(userid);
				return resp;//Resps.json(request, resp);
			} else {
				log.info("{} session中并未绑定userid", request.getChannelContext());
			}
		} else {
			log.info("{} 不能根据sessionId[{}]找到session对象", request.getChannelContext(), sessionId);
		}

		Resp resp = Resp.fail();
		return resp;//Resps.json(request, resp);

	}

	/**
	 * 
	 * @param request
	 * @param httpConfig
	 * @param x userid
	 * @return
	 * @throws Exception
	 * @author tanyaowu
	 */
	@RequestPath(value = "/by")
	public Resp by(HttpRequest request, HttpConfig httpConfig, Integer x) throws Exception {

		if (x == null) {
			Tio.remove(request.getChannelContext(), "非法请求");
			return null;
		}

		SimpleUser simpleUser = SimpleUser.fromUid(x);
		Resp resp = null;
		if (simpleUser != null) {
			resp = Resp.ok(simpleUser);
		} else {
			resp = Resp.fail("can not found the userid");
		}
		return resp;

	}

	/**
	 * 修改昵称
	 * @param user
	 * @param request
	 * @return
	 * @throws Exception
	 * @author tanyaowu
	 */
	@RequestPath(value = "/updateNick")
	public Resp updateNick(HttpRequest request, String nick) throws Exception {
		User curr = WebUtils.currUser(request);
		if (curr == null) {
			return Resp.fail().msg("用户未登录");
		}

		return userService.updateNick(curr, nick);
	}

	/**
	 * 修改头像
	 * @param request
	 * @param uploadFile
	 * @return
	 * @throws Exception
	 * @author tanyaowu
	 */
	@RequestPath(value = "/updateAvatar")
	public Resp updateAvatar(HttpRequest request, UploadFile uploadFile) throws Exception {
		User curr = WebUtils.currUser(request);
		Resp ret = null;
		if (curr == null) {
			ret = Resp.fail("您尚未登录或登录超时").code(AppCode.ForbidOper.NOTLOGIN);
		}

		byte[] imageBytes = uploadFile.getData();
		String extName = FileUtil.extName(uploadFile.getName());

		if (UserService.isSupper(curr) || UserRoleService.hasRole(curr, Const.Role.UPLOAD_VIDEO)) {

		} else {
			int maxsize = ConfService.getInt("user.upload.avatar.maxsize", 512);

			if (imageBytes.length > 1024 * maxsize) {
				ret = Resp.fail("文件尺寸不能大于" + maxsize + "KB");
			}
		}

		Integer uid = null;
		if (curr != null) {
			uid = curr.getId();
		} else {
			uid = 1;
		}

		String imgUrlWithoutExt = UploadUtils.newFile(org.tio.sitexxx.service.vo.Const.UPLOAD_DIR.USER_AVATAR, uid, uploadFile.getName()); //不带后缀的文件路径
		String imgUrl = imgUrlWithoutExt + "." + extName;

		String smImgUrl = imgUrlWithoutExt + "_sm." + extName;

		String imgFilePath = Const.RES_ROOT + imgUrl; //文件路径
		FileUtil.writeBytes(imageBytes, imgFilePath);

		String smImgFilePath = Const.RES_ROOT + smImgUrl;

		BufferedImage bi = ImageUtil.toImage(imageBytes);
		float scale = ImgUtils.calcScaleWithWidth(168, bi);

		Img img = ImgUtils.processImg(bi, imgFilePath, smImgFilePath, scale);
		img.setComefrom(Img.ComeFrom.MODIFY_AVATAR);
		img.setUid(uid);
		img.setCoverurl(smImgUrl);
		img.setUrl(imgUrl);
		img.setStatus((byte) 1);
		img.setSession(request.getHttpSession().getId());

		boolean f = ImgService.me.save(img);

		if (ret != null) {
			return ret;
		}

		if (f) {
			return userService.updateAvatar(curr, smImgUrl, imgUrl);
		} else {
			return Resp.fail("服务器异常");
		}
	}

}
